package xyz.xtt.exchange.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import xyz.xtt.common.starter.cache.CacheManager;
import xyz.xtt.exchange.constants.ExchangeCache;
import xyz.xtt.exchange.entity.TblRegion;
import xyz.xtt.exchange.mapper.TblRegionMapper;
import xyz.xtt.exchange.service.ITblRegionService;
import xyz.xtt.exchange.vo.PhoneRegionVo;

import java.util.Collections;
import java.util.List;

/**
 * 行政区划服务
 *
 * @author dale
 * @since 2025/1/2
 **/
@Service
public class TblRegionServiceImpl extends ServiceImpl<TblRegionMapper, TblRegion> implements ITblRegionService {
    @Autowired
    private CacheManager cacheManager;

    @Override
    public List<PhoneRegionVo> getRegionList(String parentId) {
        Long pid = StringUtils.isNotBlank(parentId) ? Long.valueOf(parentId) : 0L;
        return cacheManager.cacheList(()->this.getRegionListFromDB(pid), ExchangeCache.LUCK_PHONE_REGION_LIST, parentId);
    }

    /**
     * 从数据库获取归属地列表
     * @param pid
     * @return
     */
    private List<PhoneRegionVo> getRegionListFromDB(long pid) {
        QueryWrapper<TblRegion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", pid);
        queryWrapper.eq("is_del",0);
        queryWrapper.orderByAsc("region_pinyin");
        List<TblRegion> list = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(list)){
            return Collections.emptyList();
        }
        return list.stream().map(region -> new PhoneRegionVo(region.getId().toString(), region.getRegionName(), region.getRegionLevel())).toList();
    }
}
